<script setup>
import SmtHeader from '@/layout/SmtHeader.vue';
import SmtFooter from '@/layout/SmtFooter.vue';
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  getBomMatchListStatisticsData,
  getAgainMatchBom,
  fileProcessingProgress,
} from '@/server/api/biz.js';
import { IbeStocking, NotAttached, Unmatched } from './TasbView';
import { confirmMatchOrder } from '@/server/api/bom.js';
// import SelectModal from './TabViews/SelectModal.vue';
import { ArrowDown } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import useAppStore from '@/store/modules/app';
import useOrderStore from '@/store/modules/order';
import { debounce } from 'lodash';

const { t } = useI18n();
const orderStore = useOrderStore();
const route = useRoute();
const router = useRouter();
const appStore = useAppStore();

let modelConfirmed = ref(0);
let totalBomAmount = ref(0);
let singleBomAmount = ref(0);
let expiredTime = ref(0);
let similarity = ref({});
const jumpOrderListType = ref();
let modelDetermined = ref(0);
let allType = ref(0);
const showBomConfirmBtn = ref('');

const ruleForm = reactive({
  patchNum: 0, // 贴片数量
  bomFileId: '',
  fileSerial: '',
  layer: '1', // 贴片层数(1全，2top，3bottom)
});

const orederId = ref('');

const activeTab = ref(0);

// 总数量
const totalNum = computed(() =>
  tabsList
    .filter((item, index) => index > 0)
    .map((item) => item.num)
    .reduce((cur, acc) => cur + parseInt(acc), 0),
);

// 当前选中的组件
const curComponent = computed(() => (value) => {
  const curTab = tabsList.find((item) => item.value === value);
  if (curTab) {
    return curTab;
  }
});

const tableRef = ref(null);

const tabsList = reactive([
  {
    label: t('om.All'),
    value: 0,
    num: totalNum,
  },
  {
    label: t('om.IBEstocking'),
    value: 1,
    title: t('om.IBEstocking'),
    component: IbeStocking,
    num: 0,
  },
  {
    label: t('om.Unmatched'),
    value: 2,
    title: t('om.UnmatchedComponents'),
    component: Unmatched,
    num: 0,
  },
  {
    label: t('om.Notsticker'),
    value: 3,
    title: t('om.UnpostedComponents'),
    component: NotAttached,
    num: 0,
  },
]);
/**
 * 获取统计数据
 */
const getStatisticalData = () => {
  getBomMatchListStatisticsData({
    bomFileId: ruleForm.bomFileId,
  }).then((res) => {
    if (res.code == 200) {
      totalBomAmount.value = res.data.totalBomAmount;
      singleBomAmount.value = res.data.singleBomAmount;
      expiredTime.value = res.data.expiredTime;
      similarity.value = res.data.similarity;
      modelConfirmed.value =
        Number(similarity.value['3']) +
        Number(similarity.value['4']) +
        Number(similarity.value['5']);
      modelDetermined.value = Number(similarity.value['1']) + Number(similarity.value['6']);
      // 全部型号
      allType.value = res.data.totalManufacturerPn;
      // 不贴数量
      tabsList[3].num = res.data.patchStatus['2'];
      // 未匹配
      tabsList[2].num = res.data.similarity['2'];

      // ibe备货
      tabsList[1].num = modelConfirmed.value + modelDetermined.value; // 已确定型号数 + 待确定型号数
      console.log(tableRef.value, 'ref数据');
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  const { bomFileId, patchNum, fileSerial, bomName, layer, bomConfirmShow, id, orderListType } =
    route.query;

  if (bomFileId && bomName) {
    ruleForm.bomFileId = bomFileId; // boom文件id
    ruleForm.bomName = bomName; // bom文件名称
    getStatisticalData();
  }

  if (orderStore.smtOrderInfo.orderNumber) {
    ruleForm.patchNum = orderStore.smtOrderInfo.orderNumber; // 贴片数量
  } else if (patchNum) {
    ruleForm.patchNum = patchNum;
  }

  if (orderStore.smtOrderInfo.smtLayer) {
    ruleForm.layer = orderStore.smtOrderInfo.smtLayer; // 贴片层
  } else if (layer) {
    ruleForm.layer = layer; // 贴片层
  }

  if (fileSerial) {
    ruleForm.fileSerial = fileSerial; // 文件编号
  }

  if (bomConfirmShow) {
    showBomConfirmBtn.value = bomConfirmShow;
  } else {
    showBomConfirmBtn.value = '';
  }
  if (id) {
    orederId.value = id;
  }

  // 1为SMT , 2为BOM备料
  if (orderListType) {
    jumpOrderListType.value = orderListType;
  }
});

// 上一个页面的路由名称
const prevRouteName = computed(() => {
  const previousRoute = route.query.beforeOrderType;
  return previousRoute;
});

// 列表总数变化
// const onChangeTotal = ({ type, num }) => {
//   if (type === 'IbeStocking') {
//     tabsList[1].num = num;
//   }
//   if (type === 'Unmatched') {
//     tabsList[2].num = num;
//   }
//   if (type === 'NotAttached') {
//     tabsList[3].num = num;
//   }
//   console.log('tabsList', tabsList);
// };

/**
 * 确认下单
 */
const handleSubmit = () => {
  const smtOrderInfo = orderStore.smtOrderInfo;
  orderStore.setSmtOrderInfo({
    ...smtOrderInfo,
    orderNumber: ruleForm.patchNum,
    smtLayer: ruleForm.layer,
  });
  if (Number(similarity.value['2'])) {
    ElMessage.error(t('mall.mismatched_bom'));
    return;
  }

  if (modelConfirmed.value > 0) {
    ElMessage.error(t('mall.pending_confirmation_of_bom'));
    return;
  }

  router.push({
    path: '/settlement',
  });
};

/**
 * 提交订单
 */
const handleOrder = () => {
  if (ruleForm.layer) {
    route.query.smtLayer = ruleForm.layer;
  }
  route.query.patchNum = ruleForm.patchNum;
  router.push({
    path: '/pricing/smt',
    query: route.query,
  });
};

const numList = reactive([10, 20, 30, 40, 50, 70, 100]);
const dropdownVisible = ref(false);
const isAtive = ref(false);
/**
 * 选择板子数量
 * @param item
 */
const getNumItem = (item) => {
  const { orderNumber } = route.query;
  if (orderNumber && item > Number(route.query.patchNum)) {
    return ElMessage.error(`${t('mall.smt_quantity_exceed_pcb')}${route.query.patchNum}`);
  }
  ruleForm.patchNum = item;
};

// 校验输入订单量不能大于带过来的订单量
const checkInputOrderNumber = (value) => {
  const numValue = Number(value);
  const { orderNumber } = route.query;
  if (numValue > Number(route.query.patchNum) && orderNumber) {
    ElMessage.error(`${t('mall.smt_quantity_exceed_pcb')}${route.query.patchNum}`);
    ruleForm.patchNum = route.query.patchNum;
  } else {
    ruleForm.patchNum = value;
  }
};

/**
 * 取消
 */
const handleClose = () => {
  dropdownVisible.value = false;
};

// 防抖切换
const debouncedMethod = debounce(() => {
  getAgainMatchBom({
    bomFileId: ruleForm.bomFileId,
    smtNumber: ruleForm.patchNum,
    layer: ruleForm.layer,
  }).then((res) => {
    if (res.code == 200) {
      getParsingStatus();
    } else {
      ElMessage.error(res.msg);
    }
  });
}, 500); // 设置延迟时间，单位为毫秒
/**
 * 确定
 */

const handleConfirm = () => {
  dropdownVisible.value = false;

  debouncedMethod();
};

/**
 * 获取处理状态
 */
const getParsingStatus = () => {
  fileProcessingProgress(ruleForm.bomFileId).then((res) => {
    if (res.code == 200) {
      if (res.data.parseStatus == 4) {
        getStatisticalData();
        ElMessage.success(t('mall.reassignment_successful'));
      }
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const open = () => {
  dropdownVisible.value = !dropdownVisible.value;
};

// 深度匹配，才会出现的BOM确认按钮（SMT订单或BOM备料）
const handleBomConfirm = async () => {
  if (jumpOrderListType.value === '1') {
    const { code } = await confirmMatchOrder(orederId.value);
    if (code === 200) {
      router.push({ path: '/order', query: { type: 0, tabs: 0 } });
    }
  } else {
    if (modelConfirmed.value > 0) {
      ElMessage.error(t('mall.pending_confirmation_of_bom'));
      return;
    }
    router.push({ path: '/order', query: { type: 0, tabs: 2 } });
  }
};

// 去支付
const toPayment = async () => {
  // 先确认bom验证成功后，才到支付页面
  const { code } = await confirmMatchOrder(orederId.value);
  if (code === 200) {
    if (modelConfirmed.value > 0) {
      ElMessage.error(t('om.pending_confirmation_of_bom'));
      return;
    }
    router.replace({
      path: '/payment',
      query: {
        id: route.query.id,
      },
    });
  }
};
</script>
<template>
  <!-- 头部 -->
  <smt-header></smt-header>
  <div class="wrapper">
    <div class="quotation container">
      <div class="breadcrumb-wrap" style="margin-bottom: 20px; margin-left: 20px">
        <el-breadcrumb :separator-icon="ArrowRight" class="f-28">
          <el-breadcrumb-item :to="{ path: '/' }">{{ $t('menu.home') }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $t('om.BOMMatchingOrderOnlineQuotation') }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 基本信息容器 -->
      <div class="info-block">
        <el-row type="flex" align="center" style="margin-bottom: 20px">
          <el-col :span="6">
            <div class="block-row">
              <span class="label">{{ $t('om.BOMCode') }} ： </span>
              <span class="desc"> {{ ruleForm.fileSerial }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="block-row">
              <span class="label">{{ $t('smt.AllModels') }}： </span>
              <span class="desc"> {{ allType }}</span>
            </div>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row">
              <span class="label">{{ $t('smt.Numberofmodelsidentified') }}： </span>
              <span class="desc"> {{ modelDetermined }}</span>
            </div>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row">
              <span class="label">{{ $t('smt.Numberofmodelstobedetermined') }}： </span>
              <span class="desc"> {{ modelConfirmed }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row type="flex" align="center" style="margin-bottom: 20px">
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row">
              <span class="label">{{ $t('smt.Numberofunmatchedmodels') }}： </span>
              <span class="desc"> {{ Number(similarity['2']) }}</span>
            </div>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row" style="display: flex; align-items: center">
              <span class="label">{{ $t('smt.patchQuantity') }} ：</span>
              <el-popover :visible="dropdownVisible" placement="bottom">
                <template #reference>
                  <div :class="isAtive ? 'active' : 'count-but'" @click="open">
                    <span>{{ ruleForm.patchNum }}</span>
                    <el-icon><ArrowDown /></el-icon>
                  </div>
                </template>
                <template #default>
                  <div class="num-list">
                    <ul>
                      <li
                        class="num-list-item"
                        v-for="item in numList"
                        :key="item"
                        @click="getNumItem(item)"
                      >
                        {{ item }}
                      </li>
                    </ul>
                  </div>
                  <p class="m-t-16">{{ $t('bom.Otherquantities') }}</p>
                  <el-input
                    class="m-t-16"
                    v-model="ruleForm.patchNum"
                    v-number
                    :maxlength="8"
                    :placeholder="$t('bom.Pleaseenterthenumber')"
                    @input="checkInputOrderNumber"
                  />
                  <div class="footer m-t-16">
                    <el-button type="primary" @click="handleConfirm">{{
                      $t('smt.Define')
                    }}</el-button>
                    <el-button @click="handleClose">{{ $t('smt.Cancel') }}</el-button>
                  </div>
                </template>
              </el-popover>
            </div>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row">
              <span class="label">{{ $t('om.Estimatedtotalprice') }} ： </span>
              <span class="desc red"> $ {{ totalBomAmount.toFixed(2) }} </span>
            </div>
          </el-col>
          <el-col :span="6" style="display: flex; align-items: center">
            <div class="block-row">
              <span class="label">{{ $t('om.Quotationvaliditytime') }} ：</span>
              <span class="desc green"> {{ expiredTime || $t('PCB.Notavailable') }} </span>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <div class="block-row">
            <span class="label">{{ $t('smt.chipLayer') }} ：</span>
            <div class="radio-group-wrap">
              <el-radio-group v-model="ruleForm.layer" @change="handleConfirm">
                <el-radio label="1" border>{{ $t('smt.topAndBottom') }}</el-radio>
                <el-radio label="2" border>{{ $t('smt.topPostingOnly') }}</el-radio>
                <el-radio label="3" border>{{ $t('smt.bottomLayerOnly') }}</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-row>
      </div>
      <!-- 贴片列表 -->
      <!-- <QuotationView :fileId="ruleForm.bomFileId" /> -->
      <div class="table-container">
        <!-- tab 容器 -->
        <div class="tab-wrap">
          <el-radio-group v-model="activeTab">
            <el-radio-button v-for="item in tabsList" :key="item.value" :label="item.value">
              <template #default
                >{{ item.label }} <span>({{ item.num }})</span></template
              >
            </el-radio-button>
          </el-radio-group>
        </div>
        <template v-if="activeTab === 0">
          <div class="talbe-wrap" v-for="(tab, index) in tabsList" :key="index">
            <component
              :is="tab.component"
              :title="tab.title"
              :params="{ quantity: ruleForm.patchNum }"
              @resetStatisticalData="getStatisticalData"
            />
          </div>
        </template>
        <div v-else class="talbe-wrap">
          <component
            ref="tableRef"
            :is="curComponent(activeTab).component"
            :title="curComponent(activeTab).title"
            :params="{ bomFileId: route.query.bomFileId }"
            @resetStatisticalData="getStatisticalData"
          />
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="btn-wrap">
        <el-button plain @click="$router.back()">{{ $t('mall.previous_step') }}</el-button>

        <template v-if="showBomConfirmBtn">
          <el-button plain type="primary" @click="handleBomConfirm">{{
            $t('mall.confirm_bom')
          }}</el-button>
        </template>
        <template v-if="['smt'].includes(prevRouteName)">
          <el-button type="primary" @click="handleSubmit()">{{
            $t('mall.confirm_order')
          }}</el-button>
        </template>
        <template v-if="['bom', 'bomView'].includes(prevRouteName)">
          <el-button type="primary" @click="handleOrder()">{{
            $t('mall.proceed_to_smt_order')
          }}</el-button>
        </template>
        <template v-if="['smtOrderList'].includes(prevRouteName)">
          <el-button plain type="primary" @click="toPayment">去支付</el-button>
        </template>
      </div>
    </div>
  </div>
  <!-- 底部 -->
  <smt-footer></smt-footer>

  <!-- <SelectModal
    v-model="modelValue"
    :patchNum="ruleForm.patchNum"
    :fileId="ruleForm.bomFileId"
    :flieData="flieData"
  /> -->
</template>
<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
:global(.el-popover.el-popper) {
  min-width: 300px;
}
.m-t-16 {
  margin-top: 16px;
}
.num-list {
  width: 284px;
  ul {
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 6px;
    .num-list-item {
      width: 56px;
      height: 29px;
      line-height: 29px;
      text-align: center;
      border-radius: 4px;
      background: #f0f0ff;
      cursor: pointer;
    }
  }
}
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 14px;
}

.btn-wrap {
  display: flex;
  justify-content: center;
  padding: 30px;
}
.f-14 {
  font-size: 14px;
}
.m-t-16 {
  margin-top: 16px;
}
.count-but {
  width: 110px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  text-align: center;
  border: 1px solid var(--mall-border-color);
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  box-sizing: border-box;
}
.active {
  width: 110px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  text-align: center;
  border: 1px solid var(--mall-color-primary);
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  box-sizing: border-box;
}
.more {
  width: 56px;
  height: 29px;
  border-radius: 4px;
  opacity: 1;
  background: #f0f0ff;
  line-height: 29px;
  text-align: center;
  cursor: pointer;
}
.wrapper {
  padding: 12px 0 72px;
  background: #f5f5f5;
  .btn {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    .el-button {
      width: 200px;
      height: 40px;
      border-radius: 4px;
      margin: 0 162px;
      background-color: var(--mall-color-primary);
      color: var(--mall-header-bg);
    }
  }
  .quotation {
    padding: 24px 0;
    border-radius: 8px;
    background: #fff;
    border-bottom: 1px solid #f5f5f5;
    &.container {
      width: 1440px;
      margin: 0 auto;
    }

    .page-title {
      padding: 0 24px 12px;
      color: var(--mall-text-color-primary);
      font-size: 20px;
      font-weight: 700;
    }

    .info-block {
      margin: 20px;
      padding: 20px;
      border: 1px solid var(--mall-border-color);
      border-radius: 6px;
    }

    .block-row {
      display: flex;
      align-items: center;
      .label {
        font-size: 14px;
        color: #666666;
      }
      .desc {
        font-size: 14px;
        color: #666666;
        &.red {
          color: #ff4d4f;
        }
        &.yelow {
          color: #faad14;
        }
        &.green {
          color: #52c268;
        }
      }
    }

    .content-wrap {
      padding: 24px;
      .tab-wrap {
        padding: 0 15px;
      }
    }
  }
}

::v-deep .el-radio-group {
  .el-radio {
    &.is-bordered {
      margin-bottom: 0;
      &:not(.is-checked) {
        .el-radio__label {
          color: #666666;
        }
      }
    }
  }
}

.table-container {
  .tab-wrap {
    padding: 0 40px;
  }
  .talbe-wrap {
    padding: 0 20px;
  }
}
</style>
